#include "../include/dir.h"


int handle_ls(path_t *path, const char *destDir, char *buf, int buf_len){
    //清空buf 避免调用了多次带buf的函数后面会输出前面buf内容 测试问题mkdir->ls
    bzero(buf, buf_len);
    
    char newVirPath[MAX_PATH_LEN] = {0};
    char newRealPath[MAX_PATH_LEN] = {0};

    makePath(path, destDir, newVirPath, newRealPath);
    
    DIR *dirp = opendir(newRealPath);
    if(!dirp){
        sprintf(buf, "无法打开目录:%s\n", strerror(errno));
        return -1;
    }

    //开始读目录 打印
    struct dirent *entry;
    while((entry = readdir(dirp))){
        char tempPath[MAX_PATH_LEN] = {0}; //用来判断是不是目录
        sprintf(tempPath, "%s/%s", newRealPath, entry->d_name);

        //stat获取文件信息
        struct stat st;
        stat(tempPath, &st);
        int len = buf_len-strlen(buf)-1;
        if(S_ISDIR(st.st_mode)){
            //是目录
            strncat(buf, entry->d_name, len);
            len = buf_len-strlen(buf)-1;
            strncat(buf, "/\n", len);
        }
        else{
            strncat(buf, entry->d_name, len);
            len = buf_len-strlen(buf)-1;
            strncat(buf, "\n", len);
        }
    }
    
    closedir(dirp);

    return 0;
}
